<?php

class SiteController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
	public $layout="tplexlayout";
	public $objUser="";
	public $owner="";
	protected $_identity;
 	public $_logouturl;
 	
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
		$this->redirect('admin/profile/profile');
	}
	
	public function actionSearchcuisine($category)
	{
		$sql = "SELECT distinct(r.name)
			FROM tplex_restaurant r, tplex_restaurant_menu_mapping m, tplex_menu_category c 
			WHERE m.id_menu_category = c.id AND m.id_restaurant = r.id AND c.name = '". $category ."'";
		$command=Yii::app()->db->createCommand($sql);
		$list=$command->queryAll();
		echo "<pre>"; print_r($list); exit;				
		$this->render('searchcuisine',array('category'=>$category));
	}
	
	public function actionSearchresult()
	{
			$criteria = Restaurant::getCriteria('BY-SEARCH', $_GET);
			$url = Yii::app()->request->requestUri;
			ApplicationSessions::run()->write('url',$url);
			$dataProvider=new CActiveDataProvider('Restaurant', array(
                'pagination'=>array(
                 'pageSize'=>10,
                ),
                'criteria'=>$criteria,
        		));
			$this->render('searchresult',array('dataProvider'=>$dataProvider,'arrParams'=>$_GET));
	}
	
	public function actionRestaurant($id,$price=0)
	{
	  $session = new CHttpSession();
    $session->open();
    $session['referer_uri'] = Yii::app()->createAbsoluteUrl('site/restaurant/id/'.$id.'/price/'.$price ); 
	//echo $session['referer_uri']; exit;
    $cart_id = ApplicationSessions::run()->read('cart_id');
		
		if(!isset($cart_id))
		{
			$maxID = Yii::app()->db->createCommand()
  							->select('max(id) as max')
  							->from('cart')
  							->queryScalar();
  			$maxID = $maxID+1;
  			
			ApplicationSessions::run()->write('cart_id',$maxID);
		}
		$model = Restaurant::model()->getModel('BY-SLUG', array('id'=>$id));
		$veg_categories = RestaurantMenuMapping::getList('RESTAURANT-VEG', array('id'=>$model->id));
		$non_veg_categories = RestaurantMenuMapping::getList('RESTAURANT-NON-VEG', array('id'=>$model->id));
		$this->render('restaurant', array('model'=>$model, 'veg_categories'=>$veg_categories, 'non_veg_categories'=>$non_veg_categories,'price'=>$price));
	}
	
	public function actionGetLocation()
    {
		 if (!empty($_GET['term'])) 
		 {
		 	$arrFinal = array();
		 	$qterm = $_GET['term'].'%';
		 	
			$sql1 = 'SELECT z.id, z.slug, z.name as value, z.name as label, s.name as sname FROM tplex_zones `z`,tplex_suburb `s` WHERE s.name LIKE :qterm AND z.id_suburb=s.id';
			$sql1 .= ' ORDER BY s.name,z.name';
			$command1 = Yii::app()->db->createCommand($sql1);
			$command1->bindParam(":qterm", $qterm, PDO::PARAM_STR);
			$result1 = $command1->queryAll();
			
			$sql = 'SELECT z.id, z.slug, z.name as value, z.name as label, s.name as sname FROM tplex_zones `z`,tplex_suburb `s` WHERE z.name LIKE :qterm AND z.id_suburb=s.id';
			$sql .= ' ORDER BY s.name,z.name';
			$command = Yii::app()->db->createCommand($sql);
			$command->bindParam(":qterm", $qterm, PDO::PARAM_STR);
			$result = $command->queryAll();
			$i = 0;
			foreach ($result1 as $loc) {
				$arrFinal[$i]['id'] = $loc['slug'];
				$arrFinal[$i]['value'] = $loc['sname'].", ".$loc['value'];
				$arrFinal[$i]['label'] = $loc['sname'].", ".$loc['label'];
				$arrFinal[$i]['category'] = "zone";
				$i++;
			}
			$j = sizeof($result1);
		 	foreach ($result as $loc) {
				$arrFinal[$j]['id'] = $loc['slug'];
				$arrFinal[$j]['value'] = $loc['sname'].", ".$loc['value'];
				$arrFinal[$j]['label'] = $loc['sname'].", ".$loc['label'];
				$arrFinal[$j]['category'] = "zone";
				$j++;
			}
			
			echo CJSON::encode($arrFinal); exit;
		  } 
		  else 
		  {
			return false;
		  }
    }
    
    public function actionSearchrest()
    {
    	 if (!empty($_GET['term'])) 
		 {
		 	$term = trim($_GET['term']);
		 	$qterm = $_GET['term'].'%';
            $location= $_GET['location'];
            
			$sql = 'SELECT slug, id, name as value, name as label FROM tplex_restaurant WHERE name LIKE :qterm AND status = "active"';
			if($location != "") 
				$sql .= 'OR id_suburb = :location OR id_zone = :location';
			$sql .= ' ORDER BY name ASC';
			$command = Yii::app()->db->createCommand($sql);
			$command->bindParam(":qterm", $qterm, PDO::PARAM_STR);
			if($location != "")
				$command->bindParam(":location", $location, PDO::PARAM_STR);
			$result = $command->queryAll();

			$sql1 = 'SELECT slug, id, name as value, name as label FROM tplex_cuisine WHERE name LIKE :qterm';
			$sql1 .= ' ORDER BY name ASC';
			$command1 = Yii::app()->db->createCommand($sql1);
			$command1->bindParam(":qterm", $qterm, PDO::PARAM_STR);
			$result1 = $command1->queryAll();
			
			$i = 0;
			$arrFinal[$i]['id'] = 0;
			$arrFinal[$i]['value'] = 'Cuisines';
			$arrFinal[$i]['label'] = 'Cuisines';
			$arrFinal[$i]['category'] = "cuisine";
			$i = $i+1; 
			foreach ($result1 as $loc) 
			{
				$arrFinal[$i]['id'] = $loc['slug'];
				$arrFinal[$i]['value'] = $loc['value'];
				$arrFinal[$i]['label'] = $loc['label'];
				$arrFinal[$i]['category'] = "cuisine";
				$i++;
			}
			
			$j = sizeof($result1) + 1;
			$arrFinal[$j]['id'] = 0;
			$arrFinal[$j]['value'] = 'Restaurants';
			$arrFinal[$j]['label'] = 'Restaurants';
			$arrFinal[$j]['category'] = "restaurant";
			$j = $j+1;
		 	foreach ($result as $loc) 
		 	{
				$arrFinal[$j]['id'] = $loc['slug'];
				$arrFinal[$j]['value'] = $loc['value'];
				$arrFinal[$j]['label'] = $loc['label'];
				$arrFinal[$j]['category'] = "restaurant";
				$j++;
			}
			
			echo CJSON::encode($arrFinal); exit;
		 }
    	 else 
    	 {
    	 	return false;
    	 }
    }
    
    public function actionUpdateItems($slug,$type,$id) 
    {
    	$model = MenuCategory::model()->getModel('BY-SLUG', array('slug'=>$slug));
    	$sql = 'SELECT i.name, i.description, m.menu_item_price, i.slug, i.id
				FROM tplex_restaurant_menu_mapping m, tplex_menu_item i 
				WHERE m.id_restaurant = '. $id .' 
					AND m.id_menu_item = i.id 
					AND i.id_menu_category = '. $model->id .'
					AND i.type = "'. $type .'"';
    	$command = Yii::app()->db->createCommand($sql);
		$result = $command->queryAll();
		
		$restaurant = Restaurant::model()->findByPk($id);
		echo '<div class="order_detail">';
		echo "<div class='add_detail'> You are ordering from " .$restaurant->name." , ". Zones::model()->getZoneNameByID($restaurant->id_zone).", ". Suburb::model()->getSuburbNameByID($restaurant->id_suburb)."</div>";
		echo '<div class="buttons">
                	<div class="leftarrow"><img src="'. ApplicationConfig::app()->params['theme']['imageUrl'].'arrow_yellow.gif"  alt="" /></div>
                    
                	<div class="boxyellow">
                    <p style="padding-top: 15px;">Click list to see other items</p>
					</div>
                    
                    <div class="boxgrey">
                    <p style="padding-top: 4px;">Click <img src="'.ApplicationConfig::app()->params['theme']['imageUrl'].'add-fav-1.png" style="position: relative; top:4px; padding: 0 2px;" /> to add item <br/> to your order</p>
                    </div>
                    
                    <div class="boxgrey" style="border-right:none !important">
                   <p> Click checkout to <br/>complete your order</p>

                    </div>
                    
                    <div class="leftarrow"><img src="'. ApplicationConfig::app()->params['theme']['imageUrl'].'arrow_grey.gif"  alt="" /></div>
            	</div>';
		if($type == 'non-veg')
				$color = 'style="color: #854817;"';
			else
				$color = "";
				
		echo '<div class="cat_detail">Currently showing <span class="vegi" '.$color.'>'.ucfirst($type).'</span> items from <strong>'.$model->name.'</strong> category.</div>';
		if(count($result)>0)
		{
			echo '<table width="100%" border="0" cellspacing="0" cellpadding="0">';
			foreach ($result as $item) 
			{
				if(count(ItemAttributeRestaurantMapping::getList('RESTAURANT', array('id'=>$item['id'],'restaurant_id'=>$id))) > 0)
				{
					$url = Yii::app()->createUrl('site/attributesForm/id/'.$item['id'].'/restaurant_id/'.$id);
				}
				else 
				{
					$url = "#";
				}
				echo '<tr>';
		        echo '<td class="content"><h3 '.$color.'>'.$item['name'].'</h3>';
		        echo $item['description'];
				echo '<br clear="all" /></td>';
				echo '<td class="rate"><span class="WebRupee">Rs.</span> '.$item['menu_item_price'].'</td>';
		       // echo '<td class="txtbox"><input name="item_'.$item['id'].'" type="text" value="1" style="width:25px; height:25px;"/></td>';
		        echo '<td class="add"><a href="'.$url.'" id="item'.$item['id'].'"><img src="'.ApplicationConfig::app()->params['theme']['imageUrl'].'add-fav.jpg" />';
		        //echo CHtml::ajaxLink('Add',	array('site/addToCart'), array('update'=>'#order_list'));
		        echo '</a>';
		        echo '</td></tr>';
		        if(count(ItemAttributeRestaurantMapping::getList('RESTAURANT', array('id'=>$item['id'],'restaurant_id'=>$id))) == 0)
		        {
			        echo "<script type='text/javascript'>";
			        echo 'jQuery(function($) {
							jQuery(\'body\').undelegate(\'#item'.$item['id'].'\',\'click\').delegate(\'#item'.$item['id'].'\',\'click\',function(){jQuery.ajax({\'url\':\''.Yii::app()->createUrl('site/addToCart/id/'.$item['id'].'/restaurant/'.$id.'/qty/1').'\',\'cache\':false,\'success\':function(html){jQuery("#order_list").html(html)}});return false;});
			 				});';       
			        echo "</script>";
		        }
		        else 
		        {
		        	echo "<script type='text/javascript'>";
			        echo "jQuery(function($) {
							$('a#item".$item['id']."').fancybox({'type':'iframe','width':819,'min-height':204,'border':0,'autoScale':false,'scrolling':'yes','titleShow':true,'centerOnScroll':true});
			 				});";       
			        echo "</script>";
		        }
			}
			echo '</table>';
			
		}
		else
		{
			echo '<table width="100%" border="0" cellspacing="0" cellpadding="0">';
			echo '<tr>';
			echo '<td class="content"><h3>No Menu Items Found</h3></td>';
			echo '</tr>';
			echo '</table>';
		}
		Yii::app()->end();
    }
    
    public function actionRestaurantOwnerInfo() 
    {
    	$this->layout="fancylayout";
    	$model= new RestaurantOwnerInfo();
    	if (!empty($_POST['RestaurantOwnerInfo']))
    	{
    		$model->attributes=$_POST['RestaurantOwnerInfo'];
    		if ($model->validate())
    		{
    			$model->save();
    			$this->redirect(array('thank'));
    			//echo '<script type="text/javascript"> parent.$.fancybox.close();</script>';
    		}
    	}
    	$this->render('restaurantOwnerForm',array('model'=>$model));
    }
    
    public function actionThank() {
    	$this->layout = 'fancylayout';
    	$this->render('thank');
    }
    public function actionClosed_status($id,$loc_type) 
    {
    	$this->layout="fancylayout";
    	
    	if (isset($_POST['yes']) && $_POST['yes'] == 'yes')
    	{
    		if ($loc_type=="all")
    		{
	            echo '<script>window.parent.location.href="'.Yii::app()->createUrl("site/deliveryArea/id/".$id).'";</script>';
    		}
	        else            	
	        {
	        	$restaurant = Restaurant::model()->findByPk($id);           	
	        	echo '<script>window.parent.location.href="'.Yii::app()->createUrl("site/restaurant/id/".$restaurant->slug).'";</script>';
	        }
    	}
    	if (isset($_POST['no']) && $_POST['no'] == 'no')
    	{
    		echo '<script type="text/javascript"> parent.$.fancybox.close();</script>';
    	}
    	
    	$this->render('closed_status',array('id'=>$id,'loc_type'=>$loc_type));
    }
    
    public function actionUpdateInfo($slug,$type)
    {
    	$model = Restaurant::model()->getModel('BY-SLUG', array('id'=>$slug));
    	$contact = $model->landline1;
    	if(isset($model->landline2) && $model->landline2 != "") 
    		$contact .= " / " . $model->landline2;
       	if(isset($model->landline3) && $model->landline3 != "") 
    		$contact .= " / " . $model->landline3;
    	if(isset($model->landline4) && $model->landline4 != "") 
    		$contact .= " / " . $model->landline4;
    		
    	$day = date("l");	
    	$op_timings = RestaurantOperationsTiming::model()->getModel('BY-RESTAURANT-ID', array('id'=>$model->id,'day'=>$day));
    	$delivery_timing = RestaurantDeliveryTiming::model()->getList('OPERATIONAL-TIMING', array('operationaltimingid'=>$op_timings->id));
    	$time = "";
    	if(!empty($delivery_timing))
    	{
	    	foreach ($delivery_timing as $dt) {
	    		$time .= $dt->start_time . " To " .$dt->end_time."<br/>";
	    	}
    	}
    	if($type = 'info')
    	{ 
		echo "<div class='item_info'>";
             echo "<div class='add_detail'><div class='call'>Call : ".$contact."</div></div>";
			 echo '<div class="add_detail"><span>Delivery Timing :  <span class="think"> '.$time.' </span></span></div>
                <div class="add_detail"><span>Minimum Order :  <span class="think"> Rs. '.$model->minimum_order.'</span></span></div>
                <div class="add_detail"><span>Delivery Conditions :  <span class="think">'.$model->delivery_conditions.'</span></span></div>		
                <div class="deltime">Approximate Home Delivery Time:<br />
                           <span class="think"> Weekdays: '. $model->app_delivery_timing_weekday .'<br />
                            Weekend: '.$model->app_delivery_timing_weekend.'</span>
				</div>';
			echo '</div>';
    	}
    	
    	Yii::app()->end();
    }
    
    public function actionProfile() 
    {
    	$this->layout="profilelayout";
    	$id = ApplicationSessions::run()->read('customer_id');
    	$model = Customers::model()->findByPk($id);
    	$this->objUser=$model;
    	if (isset($_POST['Customers']))
    	{
    		$model->attributes = $_POST['Customers'];
    		
    		/*$modelObject=CUploadedFile::getInstance($model,'logo');			
			if (!empty($modelObject))
			{
				$image_name = md5($modelObject->name).'.'.substr($modelObject->type,6); 
				$model->logo=$image_name;
				$modelObject->saveAs( ApplicationConfig::app()->params['folder_path']['profileImages'].$image_name);
			}*/
			$model->date_of_birth  = $_POST['Customers']['date_of_birth'];
    		if ($model->save())
    		{
    			Yii::app()->user->setFlash('profileupdate','Profile Updated Successfully');
    		}   	
    	}
    	
    	$this->render('profile',array('model'=>$model));
    }

    public function actionCustomerPassword() 
    {
    	$this->layout="profilelayout";
    	$id = ApplicationSessions::run()->read('customer_id');
    	$model = Customers::model()->findByPk($id);
    	$model->scenario="changepassword";
    	$this->objUser=$model;
		if(!empty($_POST['Customers']))
		{
			$model->attributes=$_POST['Customers'];
			if($model->validate())
			{
				$model->password=md5($model->password);
				$model->scenario="";
				$model->save();	
				Yii::app()->user->setFlash('changepassword','Password Changed Successfully');
				
			}
		}
    	$this->render('customer_password',array('model'=>$model));
    }
    
    public function actionCustomerContactDetails() 
    {
    	$this->layout="profilelayout";
    	$id = ApplicationSessions::run()->read('customer_id');
    	$model = Customers::model()->findByPk($id);
    	$address = CustomerDeliveryAddress::model()->findByAttributes(array('id_customer'=>$id));
    	$this->objUser=$model;
 			if(isset($_POST['CustomerDeliveryAddress']))
  		{
	   		$address->attributes=$_POST['CustomerDeliveryAddress'];
		  	$address->address1 = $_POST['CustomerDeliveryAddress']['address1'];
    		$address->address2 = $_POST['CustomerDeliveryAddress']['address2'];
    		$address->id_suburb = $_POST['CustomerDeliveryAddress']['id_suburb'];
    		$address->id_zone = $_POST['CustomerDeliveryAddress']['id_zone'];
    		$address->id_state = $_POST['CustomerDeliveryAddress']['id_state'];
    		$address->id_city = $_POST['CustomerDeliveryAddress']['id_city'];
			  $address->pin_code = $_POST['CustomerDeliveryAddress']['pin_code'];
  			if($address->save())
  			{
  				//Yii::app()->user->setFlash('changepassword','Adress Changed Successfully');
  				$this->render('customer_contactdetails',array('model'=>$model,'address'=>$address));
  			}
		  }

    	$this->render('customer_contactdetails',array('model'=>$model));
    }

    public function actionfavorites() 
    {
    	$this->layout="profilelayout";
    	$id = ApplicationSessions::run()->read('customer_id');
    	$model = Customers::model()->findByPk($id);
    	$this->objUser=$model;
    	$favorites = Favorites::model()->getList('BY-CUSTOMER-ID',array('customerid'=>$id));
    	$this->render('customer_favorites',array('favorites'=>$favorites));
    }
    
    public function actionDeleteFav($id) 
    {
    	$this->layout="profilelayout";
    //	$id = ApplicationSessions::run()->read('customer_id');
    //	$model = Customers::model()->findByPk($id);
    //	$this->objUser=$model;
		Favorites::model()->findByPk((int)$id)->delete();
		$this->redirect(ApplicationConfig::getURL("", "site", "favorites"));
    }
    
    public function actionOrderHistory() 
    {
    	$this->layout="profilelayout";
    	$id = ApplicationSessions::run()->read('customer_id');
    	$model = Customers::model()->findByPk($id);
    	$this->objUser=$model;
    	$history = Orders::model()->getList('BY-CUSTOMER-ID',array('customerid'=>$id));
    	$this->render('customer_order_history',array('history'=>$history));
    }
    
    public function actionOrderForm($type) 
    {
    	$this->layout = "fancylayout";
    	$validate = false;

   		$customer_id = ApplicationSessions::run()->read('customer_id');
  		if(isset($customer_id)) 
  			$customer = Customers::model()->findByPk($customer_id);
  		else 
  			$customer = new Customers();
		
  		$address = CustomerDeliveryAddress::model()->findByAttributes(array('id_customer'=>$customer->id));	
  		if(!isset($address))
      		$address = new CustomerDeliveryAddress();

    	if(isset($_POST['send_order']))
    	{
    		$customer_id = ApplicationSessions::run()->read('customer_id');
    		if($customer_id != "")
    			$validate = true;
//    		if(!isset($customer_id))
//    		{
    			
    			$customer = Customers::model()->findByAttributes(array('email_address'=>$_POST['Customers']['email_address']));
    			
    			if(empty($customer))
    			{
    				$customer = new Customers();
    				$customer->attributes=$_POST['Customers'];
	    			//$customer->firstname = $_POST['name'];
	    			$customer->lastname = "";
	    			$password = substr(microtime(),2,6);
	    			$customer->password = md5($password);
	    			//$customer->email_address = $_POST['email_id'];
	    			//$customer->mobile_no = $_POST['mobile'];
	    			//$customer->landline_no = $_POST['landline'];*/ 
	    			$customer->landline_no = $_POST['Customers']['landline_no'];
	    			$customer->mobile_no = $_POST['Customers']['mobile_no'];
	    			$customer->created = date('Y-m-d H:i:s');
	    			$customer->modified = date('Y-m-d H:i:s');
	    			$customer->status = 'active';
	    			$customer->date_of_birth = '0000-00-00';
    			  $address = new CustomerDeliveryAddress();
    				$address->attributes=$_POST['CustomerDeliveryAddress'];
    				$address->address1 = $_POST['CustomerDeliveryAddress']['address1'];
    				$address->address2 = $_POST['CustomerDeliveryAddress']['address2'];
    				$address->id_suburb = $_POST['CustomerDeliveryAddress']['id_suburb'];
    				$address->id_zone = $_POST['CustomerDeliveryAddress']['id_zone'];
    				$address->id_state = "Maharashtra";
    				$address->pin_code = 0;
    				$address->mobile_number = 0;
					  $address->validate();
	    			if($customer->validate() && $address->validate())
	    			{
	    				$validate = true;
	    				$customer_id = $customer->id;
	    				$customer->save();
/***********************Email registration, thankyou*******************************/
              $customer->password = $password;
	    				EventNotifier::setup()->customer_registration($customer);
	    				
	    				ApplicationSessions::run()->write('customer_id',$customer->id);
	    				$address->id_customer = $customer->id;
	    				$address->save();
	    			}
    			}
    			else 
    			{    			  
    			  $customer->landline_no = $_POST['Customers']['landline_no'];
    			  $customer->mobile_no = $_POST['Customers']['mobile_no'];
    			  $customer->save();
    				$customer_id = $customer->id;
    				ApplicationSessions::run()->write('customer_id',$customer_id);
    				$customer->attributes=$_POST['Customers'];
    			 	$address = CustomerDeliveryAddress::model()->findByAttributes(array('id_customer'=>$customer->id));
    				if(!isset($address))
    				{
    					$address = new CustomerDeliveryAddress();
    				}
    				$address->attributes=$_POST['CustomerDeliveryAddress'];
    				$address->address1 = $_POST['CustomerDeliveryAddress']['address1'];
    				$address->address2 = $_POST['CustomerDeliveryAddress']['address2'];
    				$address->id_suburb = $_POST['CustomerDeliveryAddress']['id_suburb'];
    				$address->id_zone = $_POST['CustomerDeliveryAddress']['id_zone'];
    				$address->id_state = "Maharashtra";
    				$address->pin_code = 0;
    				$address->mobile_number = 0;
					  $address->validate();
	    			if($customer->validate() && $address->validate())
	    			{
	    				$validate = true;
	    				$customer->save();
	    				$address->id_customer = $customer->id;
	    				
	    				$address->save();
	    				$customer->save();
	    				
	    			}
    			}   					
//    		}
    		
    		if($validate == true)
    		{
		    		$order_id = ApplicationSessions::run()->read('order_id');
		    		
		    		if(isset($order_id))
		    			$order = Orders::model()->findByPk($order_id);
		    		else 
		    			$order = new Orders(); 	
		    		
		    		$order->order_id = substr(microtime(),2,6);
		    		$order->id_cart = ApplicationSessions::run()->read('cart_id');
		    		$order->id_customer = $customer->id;
		    		$order->id_address_delivery = $address->id;
		    		
		    		$cart = Cart::model()->findByPk(ApplicationSessions::run()->read('cart_id'));
					//var_dump($_POST);
		    		if($_POST['payment_mode'] == "card_payment")
		    			$_POST['payment_mode'] = 'EBS';
		    		$order->payment_mode = $_POST['payment_mode'];
  		    	$order->secure_key = $_POST['instructions'];
		    		$order->id_restaurant = $cart->id_restaurant;
		    		if($_POST['payment_mode'] == 'COD')
		    		{
		    			if(!isset($_POST['txtChange']))
		    				$_POST['txtChange'] = 0;
		    			$order->change = $_POST['txtChange'];
		    		}
		    		
		    		if($_POST['time'] == 'schedule')
		    		{
		    			if($_POST['delivery_date'] == "")
		    				$_POST['delivery_date'] = '0000-00-00';
		    			if(!isset($_POST['hour']))
		    				$_POST['hour'] = '00';
		    			if(!isset($_POST['minutes']))
		    				$_POST['minutes'] = '00';	
		    			$order->order_date = $_POST['delivery_date'];
		    			$order->order_time = $_POST['hour'].":".$_POST['minutes']." ".$_POST['ampm'];
		    		}
		    		
		    		$order->modified = date('Y-m-d H:i:s');
		    		$order->created = date('Y-m-d H:i:s'); 
		    		if($_POST['payment_mode'] == 'COD' || $_POST['payment_mode'] == 'sodexo')
		    			$order->status = 'processed';
/*		    		else
		    			$order->status = 'in_cart';*/
		    		$order->type = $type;
		    		$order->save();
		    		 
/***********************Order details*******************************/		    		
		    		EventNotifier::setup()->orderplaced_customer($order);
            EventNotifier::setup()->orderplaced($order);
            		    		
		    		ApplicationSessions::run()->delete('cart_id');
		    		ApplicationSessions::run()->delete('cart_count');
		    		
		    		echo '<script type="text/javascript">';
		    		//echo 'parent.$.fancybox.close();';
		    	
		    		if(	$_POST['payment_mode'] == 'COD' || $_POST['payment_mode'] == 'sodexo')
		    			echo 'window.parent.location.href="'.Yii::app()->createUrl("site/thankyou/order_id/".$order->id).'";</script>';
		    		else
		    			echo 'window.parent.location.href="'.Yii::app()->createUrl("site/ebs/order_id/".$order->id).'";</script>';
    		}
    	}

    	$this->render('orderForm',array('type'=>$type,'customer'=>$customer,'address'=>$address));

    }
  public function actionEbs($order_id)
	{
		
		$this->render('ebs',array('orderid'=>$order_id));
	}
	public function actionEbsResponse()
	{

    $this->render('ebs',array('orderid'=>$order_id));
	}
    public function actionRestaurantOwnerForm($id)
    {
    	$this->layout = 'fancylayout';
    	
    	$model = RestaurantOwnerInfo::model()->findByPk($id);
    	if(isset($_POST['RestaurantOwnerInfo']))
    	{
    		$model->attributes=$_POST['RestaurantOwnerInfo'];
    		
    		$model->save();
    		$this->redirect(array('index'));
    	}
    	$this->render('restaurantOwnerForm',array('id'=>$id,'model'=>$model));
    }
    
    public function actionAddFavorite($id)
    {
    	$customer_id = ApplicationSessions::run()->read('customer_id');
    	$model = new Favorites();
    	$model->id_customer = $customer_id;
    	$model->id_restaurant = $id;
    	$model->created = date('Y-m-d H:i:s');
    	$model->modified = date('Y-m-d H:i:s');
    	$model->save();
    	echo "<a href='#'>
	    		<img id='remove-favorite' src='".ApplicationConfig::app()->params['theme']['imageUrl'] ."/fav_star_hover.png' alt='Remove Favourite' title='Remove from your favorite restaurants'/>
	    	  </a>";
    	echo "<script type='text/javascript'>";
		echo 'jQuery(function($) {
					jQuery(\'body\').undelegate(\'#remove-favorite\',\'click\').delegate(\'#remove-favorite\',\'click\',function(){jQuery.ajax({\'url\':\''.Yii::app()->createUrl('site/removeFavorite/id/'.$id).'\',\'cache\':false,\'success\':function(html){jQuery("#favtext").html(html)}});return false;});
 				});';       
		echo "</script>";
    	Yii::app()->end();
    }
    
    public function actionRemoveFavorite($id)
    {
    	$customer_id = ApplicationSessions::run()->read('customer_id');
    	$model = Favorites::model()->findByAttributes(array('id_customer'=>$customer_id, 'id_restaurant'=>$id));
    	$model->delete();
    	
    	echo "<a href='#'>
	    		<img id='add-favorite' src='".ApplicationConfig::app()->params['theme']['imageUrl']."/fav_star.png' alt='Add Favourite' title='Add to your favourite restaurants'/>
	    	</a>";
    	echo "<script type='text/javascript'>";
		echo 'jQuery(function($) {
					jQuery(\'body\').undelegate(\'#add-favorite\',\'click\').delegate(\'#add-favorite\',\'click\',function(){jQuery.ajax({\'url\':\''.Yii::app()->createUrl('site/addFavorite/id/'.$id).'\',\'cache\':false,\'success\':function(html){jQuery("#favtext").html(html)}});return false;});
 				});';       
		echo "</script>";
    	Yii::app()->end();
    }
    
	public function actionLogin($id=null) 
    {
    	$this->layout = 'fancylayout';
    	$order_id = ApplicationSessions::run()->read('order_id');
    	$order = Orders::model()->findByPk($order_id);
    	if(isset($id) || $id != "")
    		$restaurant = Restaurant::model()->findByPk($id);
    	if(isset($_POST['login']))
    	{
    		$flag = 0;
    		$username = $_POST['username'];
    		$password = $_POST['password'];
    		
    		$model = Customers::model()->findByAttributes(array('email_address'=>$_POST['username']));
    		if($model != null)
    		{
    			if(md5($password) == $model->password)
    			{
    				ApplicationSessions::run()->write('customer_id',$model->id);
    				
	    			if(isset($id) || $id != "")
	    			{
	    				$restaurant = Restaurant::model()->findByPk($id);
			    		echo '<script type="text/javascript">';
			    		echo 'window.parent.location.href="'.Yii::app()->createUrl("site/restaurant/id/".$restaurant->slug).'";</script>';
	    			}
	    			else 
	    				$restaurant = new Restaurant();
    			}
    			else 
    				$flag = 1;
    		}
    		else 
    			$flag = 1;
    			
    		if($flag == 1)
    			Yii::app()->user->setFlash('loginMessage','Username/Password incorrect!');
    		
    	}
    	$this->render('login',array('restaurant'=>$restaurant,'order'=>$order));
    }

    public function actionFavourite_login($id=null) 
    {
    	$this->layout = 'fancylayout';
    	if(isset($_POST['login']))
    	{
    		$flag = 0;
    		$username = $_POST['username'];
    		$password = $_POST['password'];
    		
    		$model = Customers::model()->findByAttributes(array('email_address'=>$_POST['username']));
    		if($model != null)
    		{
    			if(md5($password) == $model->password)
    			{
    				ApplicationSessions::run()->write('customer_id',$model->id);
    				
	    			if(isset($id) || $id != "")
	    			{
	    				$restaurant = Restaurant::model()->findByPk($id);
			    		echo '<script type="text/javascript">';
			    		echo 'window.parent.location.href="'.Yii::app()->createUrl("site/restaurant/id/".$restaurant->slug).'";</script>';
	    			}
    			}
    			else 
    				$flag = 1;
    		}
    		else 
    			$flag = 1;
    			
    		if($flag == 1)
    			Yii::app()->user->setFlash('loginMessage','Username/Password incorrect!');
    		
    	}
    	$this->render('favourite_login');
    }
    
    public function actionLogout() 
    { 
      //exit('here');
      Yii::app()->user->logout();
    	ApplicationSessions::run()->deleteAll();
    	$this->redirect(array('index'));	
    }
    
    public function actionUpdateQuantity($id, $quantity)
    {
    	$cart_count = ApplicationSessions::run()->read('cart_count');
    	$cart_id = ApplicationSessions::run()->read('cart_id');
    	$cartItem = CartItems::model()->findByAttributes(array('id'=>$id));
    	$oldQty = $cartItem->quantity;
    	$cartItem->quantity = $quantity;
    	$cartItem->save();
    	$qty = $quantity - $oldQty;
    	if($cartItem->quantity != $quantity)
    	{
	    	$cart_count = $cart_count + $quantity;
	    	ApplicationSessions::run()->write('cart_count',$cart_count);
    	}
    	$restaurant = Cart::model()->findByPk($cart_id)->id_restaurant;
    	$rest_model = Restaurant::model()->findByPk($restaurant);
    	 $objOrder = Orders::model()->find('id = ?',array(ApplicationSessions::run()->read('order_id')));
		 $objOrder->total_price = $objOrder->total_price + ($qty * $cartItem->base_price);
			  
				$discounts =0;
			    if($rest_model->minimum_order < $objOrder->total_price)
			    	{
			    		if($rest_model->discount_type == "flat")
			    			$discounts = $rest_model->discount_value;
			    		if($rest_model->discount_type == "percentage")	 
			    			$discounts = $objOrder->total_price * $rest_model->discount_value / 100;
			    	}
		        $objOrder->tax = ($objOrder->total_price - $discounts) * $rest_model->tax/100;
			    $objOrder->discount = $discounts;
			    $objOrder->final_amount = ($objOrder->total_price - $objOrder->discount) + $objOrder->tax;
          $objOrder->save();
    	$list = CartItems::model()->findAllByAttributes(array('id_cart'=>$cart_id));
    	$total = 0;
    	$i = 1;
    	echo "<table>";
    	foreach ($list as $l)
    	{
    		$row_price = $l->base_price * $l->quantity;
        	$total += $row_price; 
    		echo "<tr>";
    		
    		if(MenuItem::model()->getMenuTypeByID($l->id_menu_item) == 'veg')
				echo '<td class="symbole"><img src="'. ApplicationConfig::app()->params["theme"]["imageUrl"] .'symbole.jpg" /></td>';
			if(MenuItem::model()->getMenuTypeByID($l->id_menu_item) == 'non-veg')
				echo '<td class="symbole"><img src="'. ApplicationConfig::app()->params["theme"]["imageUrl"] .'non-veg-symbole.jpg" /></td>';
				
	        echo '<td class="content"><h3>'. MenuItem::model()->getMenuNameByID($l->id_menu_item) .'</h3></td>';
	        echo '<td class="rate"><input type="text" value="'.$l->quantity.'" style="width:25px; height:25px;" id="menu'. $i .'"/></td>';
	        echo ' <td class="update"><a href="#" id="update'. $i .'" onclick="updateQty('. $i.','.$l['id'].',document.getElementById(\'menu'.$i.'\').value)">Update</a></td>';
	        echo '<td class="add"><a href="#"><img id="img'.$i.'" src="'. ApplicationConfig::app()->params["theme"]["imageUrl"].'deleted.png" /></a></td>';
    		echo "</tr>";
			echo '<script type="text/javascript">';
			echo 'jQuery(function($) {
					jQuery(\'body\').undelegate(\'#img'. $i .'\',\'click\').delegate(\'#img'.$i.'\',\'click\',function(){jQuery.ajax({\'url\':\''.Yii::app()->createUrl('site/deleteItem/id/'.$l['id']).'\',\'cache\':false,\'success\':function(html){jQuery("#order_list").html(html)}});return false;})
				});';       
			echo "</script>"; 
    		$i++;
    	}
    	echo "</table>";
    	echo "<div class='total'><div class='left'>Sub-total:</div>
            <div class='right'>Rs. ".$total. "</div> 
        </div>";
		
    	if($rest_model->minimum_order < $total)
    	{
    		if($rest_model->discount_type == "flat")
    			$discounts = $rest_model->discount_value;
    		if($rest_model->discount_type == "percentage")	 
    			$discounts = $total * $rest_model->discount_value / 100;
    	}
    	else 
    		$discounts = 0;
    	
    	echo "<div class='total'><div class='left'>Discounts:</div>
            <div class='right'>Rs. ".$discounts. "</div> 
        </div>";
    	
        echo "<div class='total'><div class='left'>Taxes:</div>
            <div class='right'>Rs. ". ($total - $discounts) * $rest_model->tax / 100 ."</div>
        </div>";
        
        echo "<div class='total' style='background:#c4c4c4'>
        	<div class='left'>Total:</div>
            <div class='right'>Rs. ".($total - $discounts + (($total - $discounts) * $rest_model->tax /100))."</div> 
        </div>";
    	
    	Yii::app()->end();
    }

    public function actionThankyou($order_id)
    {
      $orderdetails= Orders::model()->findByPk($order_id);
      if(isset($_GET['DR']))
      {
	     $orderdetails= Orders::model()->findByPk($order_id);
	     $secret_key = "81fb99842c66ba3a2b47bba993911311";  
	     $DR = preg_replace("/\s/","+",$_GET['DR']);
  		 $rc4 = new Crypt_RC4($secret_key);
  	 	 $QueryString = base64_decode($DR);
  		 $rc4->decrypt($QueryString);
  		 $QueryString = split('&',$QueryString);
	
  		 $response = array();
  		 foreach($QueryString as $param){
  		 	$param = split('=',$param);
  			$response[$param[0]] = urldecode($param[1]);
  		 }
	 	    //echo $response['ResponseCode']; exit;
	 	    if($response['ResponseCode']==0){
	         $orderdetails->status="processed";
           $orderdetails->save();
        }
        else
        { 
	         $orderdetails->status="payment_failure";
           $orderdetails->save();
	      }   	      
	   }
	      //ApplicationSessions::run()->deleteAll();
	      ApplicationSessions::run()->delete('order_id');
	      ApplicationSessions::run()->delete('cart_id');
	      ApplicationSessions::run()->delete('cart_count');
	      //ApplicationSessions::run()->delete('order_id');
	      
	    	$this->render('thankyou',array('order_id'=>$order_id,'orderdetails'=>$orderdetails));
    }
        
    public function actionDeleteItem($id)
    {
    	$cart_id = ApplicationSessions::run()->read('cart_id');
    	$cart_count = ApplicationSessions::run()->read('cart_count');
    	$cartItem = CartItems::model()->findByAttributes(array('id'=>$id));
    	$qty = $cartItem->quantity; 
    	$cartItem->delete();
    	$cart_count = $cart_count - $qty;
    	if($cart_count)
    	     ApplicationSessions::run()->write('cart_count',$cart_count);
    	 else  
            ApplicationSessions::run()->write('cart_count',0);  
    	$restaurant = Cart::model()->findByPk($cart_id)->id_restaurant;
    	$rest_model = Restaurant::model()->findByPk($restaurant);
    	
    	$objOrder = Orders::model()->find('id = ?',array(ApplicationSessions::run()->read('order_id')));
		  $objOrder->total_price = $objOrder->total_price - ($cartItem->quantity * $cartItem->base_price);
			   
				$discounts =0;
			    if($rest_model->minimum_order < $objOrder->total_price)
			    	{			    	
			    		if($rest_model->discount_type == "flat")
			    			$discounts = $rest_model->discount_value;
			    		if($rest_model->discount_type == "percentage")	 
			    			$discounts = $objOrder->total_price * $rest_model->discount_value / 100;
			    	}
		      $objOrder->tax = ($objOrder->total_price - $discounts) * $rest_model->tax/100;
			    $objOrder->discount = $discounts;
			    $objOrder->final_amount = ($objOrder->total_price - $objOrder->discount) + $objOrder->tax;
			    $objOrder->save(); 
			    
    	$list = CartItems::model()->findAllByAttributes(array('id_cart'=>$cart_id));
    	$total = 0;
    	$i = 1;
    	echo "<table>";
    	foreach ($list as $l)
    	{
    		$row_price = $l->base_price * $l->quantity;
        	$total += $row_price; 
    		echo "<tr>";
    		
    		if(MenuItem::model()->getMenuTypeByID($l->id_menu_item) == 'veg')
				echo '<td class="symbole"><img src="'. ApplicationConfig::app()->params["theme"]["imageUrl"] .'symbole.jpg" /></td>';
			if(MenuItem::model()->getMenuTypeByID($l->id_menu_item) == 'non-veg')
				echo '<td class="symbole"><img src="'. ApplicationConfig::app()->params["theme"]["imageUrl"] .'non-veg-symbole.jpg" /></td>';
				
	        echo '<td class="content"><h3>'. MenuItem::model()->getMenuNameByID($l->id_menu_item) .'</h3></td>';
	        echo '<td class="rate"><input type="text" value="'.$l->quantity.'" style="width:25px; height:25px;" id="menu'.$i.'"/></td>';
	        echo ' <td class="update"><a href="#" id="update'. $i .'" onclick="updateQty('. $i.','.$l['id'].',document.getElementById(\'menu'.$i.'\').value)">Update</a></td>';
	        echo '<td class="add"><a href="#"><img id="img'.$i.'" src="'. ApplicationConfig::app()->params["theme"]["imageUrl"].'deleted.png" /></a></td>';
    		echo "</tr>";
			echo "<script type='text/javascript'>";
			echo 'jQuery(function($) {
					jQuery(\'body\').undelegate(\'#img'. $i .'\',\'click\').delegate(\'#img'.$i.'\',\'click\',function(){jQuery.ajax({\'url\':\''.Yii::app()->createUrl('site/deleteItem/id/'.$l['id']).'\',\'cache\':false,\'success\':function(html){jQuery("#order_list").html(html)}});return false;})
				});';       
			echo "</script>"; 
    		$i++;
    	}
    	echo "</table>";
    	echo "<div class='total'><div class='left'>Sub-total:</div>
            <div class='right'>Rs. ".$total. "</div> 
        </div>";
    	
    	if($rest_model->minimum_order < $total)
    	{
    		if($rest_model->discount_type == "flat")
    			$discounts = $rest_model->discount_value;
    		if($rest_model->discount_type == "percentage")	 
    			$discounts = $total * $rest_model->discount_value / 100;
    	}
    	else 
    		$discounts = 0;
    	
    	echo "<div class='total'><div class='left'>Discounts:</div>
            <div class='right'>Rs. ".$discounts. "</div> 
        </div>";
    		
        echo "<div class='total'><div class='left'>Taxes:</div>
            <div class='right'>Rs. ". ($total - $discounts) * $rest_model->tax / 100 ."</div>
        </div>";
        
        echo "<div class='total' style='background:#c4c4c4'>
        	<div class='left'>Total:</div>
            <div class='right'>Rs. ".($total - $discounts + (($total - $discounts) * $rest_model->tax / 100))."</div> 
        </div>";
    	Yii::app()->end();
    }
    
  public function actionAddToCart($id,$restaurant,$qty,$price=0,$attr_list="") 
    {
    	$cart_id = ApplicationSessions::run()->read('cart_id');
    	$customer_id = ApplicationSessions::run()->read('customer_id');
    	$cart_count = ApplicationSessions::run()->read('cart_count');
    	$rest_model = Restaurant::model()->findByPk($restaurant);
    	
    	if(!isset($cart_count) || $cart_count <= 0)
    		$cart_count = 0;
    	$cart = Cart::model()->findByAttributes(array('id'=>$cart_id));
    	if($cart == null)
    	{
    		$cart = new Cart();
    		$cart->id_restaurant = $restaurant;
    		$cart->created = date('Y-m-d H:i:s');
    	}
    	$cart->modified = date('Y-m-d H:i:s');
    	$cart->save();
    	$test = ApplicationSessions::run()->read('order_id');
    	 
    	if($cart_count == 0 && !isset($test))
	    {
	    	$order = new Orders();
    		//$order->order_id = substr(microtime(),2,6);
    		$order->id_cart = ApplicationSessions::run()->read('cart_id');
    		$order->id_customer = ApplicationSessions::run()->read('customer_id');
    		$order->id_restaurant = $restaurant;
//    		$order->payment_mode = $_POST['payment_mode'];
    		$order->secure_key = '1111111';
    		$order->total_price = 0;
    		$order->modified = date('Y-m-d H:i:s');
    		$order->created = date('Y-m-d H:i:s'); 
    		if(isset($customer_id))
    			$order->status = 'in_cart';
    		else
    			$order->status = 'Initial';
    		//$order->order_time = date('H:i:s');
    		$order->save();
    		ApplicationSessions::run()->write('order_id', $order->id);
	    }
    	
	    if($cart_count > 0)
	    {
	    	if($restaurant == $cart->id_restaurant)
	    	{
		    	$model = CartItems::model()->findByAttributes(array('id_cart'=>$cart->id, 'id_menu_item'=>$id));
		    	
		    	if($model == null)
		    	{
		    		$model = new CartItems();
			    	$item = MenuItem::model()->getModel('BY-ID', array('id'=>$id));
			    	$model->id_cart = $cart->id;
			    	$model->id_menu_item = $id;
			    	$model->id_menu_category = $item->id_menu_category;
			    	$model->id_restaurant = $restaurant;
			    	$model->quantity = $qty; //$_GET['item_'.$item['id']];
			    	$model->attribute_price = $price;
			    	$model->attribute_id = $attr_list;
			    	$model->base_price = RestaurantMenuMapping::getPrice($id, $restaurant);
			    	$model->created = date('Y-m-d H:i:s');
		    	}
		    	else
		    	{
		    		$model->quantity = $model->quantity + 1;
		    	}
		    	$cart_count++;
			    $model->save();
			    
			    $objOrder = Orders::model()->find('id = ?',array(ApplicationSessions::run()->read('order_id')));
		        $objOrder->total_price = $objOrder->total_price + $model->base_price + $price;
				$discounts =0;
			    if($rest_model->minimum_order < $objOrder->total_price)
			    	{			    	
			    		if($rest_model->discount_type == "flat")
			    			$discounts = $rest_model->discount_value;
			    		if($rest_model->discount_type == "percentage")	 
			    			$discounts = $objOrder->total_price * $rest_model->discount_value / 100;
			    	}
		        $objOrder->tax = ($objOrder->total_price - $discounts) * $rest_model->tax/100;
			    $objOrder->discount = $discounts;
			    $objOrder->final_amount = ($objOrder->total_price - $objOrder->discount) + $objOrder->tax;
			    $objOrder->save(); 
			    
				ApplicationSessions::run()->write('cart_count',$cart_count);
	    	}
	    	else 
				Yii::app()->user->setFlash('loginMessage','You can not add items from multiple restaurants!');    		
	    }
	    else
	    {
	    	$cart->id_restaurant = $restaurant;
	    	$cart->save();
	    	$model = CartItems::model()->findByAttributes(array('id_cart'=>$cart->id, 'id_menu_item'=>$id));
	    	if($model == null)
	    	{
	    		$model = new CartItems();
		    	$item = MenuItem::model()->getModel('BY-ID', array('id'=>$id));
		    	$model->id_cart = $cart->id;
		    	$model->id_menu_item = $id;
		    	$model->id_menu_category = $item->id_menu_category;
		    	$model->id_restaurant = $restaurant;
		    	$model->quantity = $qty; //$_GET['item_'.$item['id']];
		    	$model->attribute_price = $price;
			    $model->attribute_id = $attr_list;
		    	$model->base_price = RestaurantMenuMapping::getPrice($id, $restaurant);
		    	$model->created = date('Y-m-d H:i:s');
	    	}
	    	else
	    	{
	    		$model->quantity = $model->quantity + 1;
	    	}
	    	$cart_count++;
		    $model->save();
		    
		     $objOrder = Orders::model()->find('id = ?',array(ApplicationSessions::run()->read('order_id')));
		     $objOrder->total_price = $objOrder->total_price + $model->base_price + $price;
			   
			 $discounts =0;
         	 if($rest_model->minimum_order < $objOrder->total_price)
		     {			    	
		    		if($rest_model->discount_type == "flat")
		    			$discounts = $rest_model->discount_value;
		    		if($rest_model->discount_type == "percentage")	 
		    			$discounts = $objOrder->total_price * $rest_model->discount_value / 100;
		     }
		        $objOrder->tax = ($objOrder->total_price - $discounts) * $rest_model->tax/100;
			    $objOrder->discount = $objOrder->discount + $discounts;
			    $objOrder->final_amount = ($objOrder->total_price - $objOrder->discount) + $objOrder->tax;
		        $objOrder->save(); 
          
			ApplicationSessions::run()->write('cart_count',$cart_count);
	    }		
			
	    $order_id = ApplicationSessions::run()->read('order_id');
    	if(isset($order_id))
    	{
		   	//$order = Orders::model()->findByAttributes(array('id_cart'=>ApplicationSessions::run()->read('cart_id')));
		   	$orderItem = OrderDetails::model()->findByAttributes(array('id_order'=>$order_id, 'id_menu_item'=>$id));
		   	
		   	if($orderItem == null)
	    	{
			   	$orderItem = new OrderDetails();
		   		$orderItem->id_order = ApplicationSessions::run()->read('order_id');
		   		$item = MenuItem::model()->getModel('BY-ID', array('id'=>$id));
		  		$orderItem->id_menu_item = $id;
		   		$orderItem->name_menu_item = MenuItem::model()->getMenuNameByID($item->id);
		   		$orderItem->id_restaurant = $model->id_restaurant;
		   		$orderItem->price_menu_item = ($model->base_price * $model->quantity) + $price;;
		   		$commission = Restaurant::model()->getModel('BY-ID', array('id'=>$model->id_restaurant))->commission_percentage;
		   		$orderItem->commission = $orderItem->price_menu_item * $commission / 100;
		   		$orderItem->quantity_menu_item = $model->quantity;
			    $orderItem->attribute_price = $price;
			    $orderItem->attribute_id = $attr_list;
		   		$orderItem->created = date('Y-m-d H:i:s');
		   		$orderItem->modified = date('Y-m-d H:i:s');
	   			$orderItem->save();
	    	}
	    	else 
	    	{
	    		$orderItem->price_menu_item = ($model->base_price * $model->quantity) + $price;
	    		$commission = Restaurant::model()->getModel('BY-ID', array('id'=>$model->id_restaurant))->commission_percentage;
		   		$orderItem->commission = $orderItem->price_menu_item * $commission / 100;
		   		$orderItem->quantity_menu_item = $model->quantity;
	    		$orderItem->save();
	    	}
    	}
			    
    	$list = CartItems::model()->findAllByAttributes(array('id_cart'=>$cart->id));
    	$total = 0;
    	$i = 1;
		
		if($attr_list == "")
		{
			if(Yii::app()->user->hasFlash('loginMessage')):
				echo '<div class="success" style="color:red;">';
				echo Yii::app()->user->getFlash('loginMessage');
				echo '</div>';
			endif;
			
	    	echo "<table>";
	    	foreach ($list as $l)
	    	{
	    		$row_price = ($l->base_price * $l->quantity) + $l->attribute_price;
	        	$total += $row_price; 
	    		echo "<tr>";
	    		
	    		if(MenuItem::model()->getMenuTypeByID($l->id_menu_item) == 'veg')
					echo '<td class="symbole"><img src="'. ApplicationConfig::app()->params["theme"]["imageUrl"] .'symbole.jpg" /></td>';
				if(MenuItem::model()->getMenuTypeByID($l->id_menu_item) == 'non-veg')
					echo '<td class="symbole"><img src="'. ApplicationConfig::app()->params["theme"]["imageUrl"] .'non-veg-symbole.jpg" /></td>';
					
		        echo '<td class="content"><h3>'. MenuItem::model()->getMenuNameByID($l->id_menu_item) .'</h3></td>';
		        echo '<td class="rate"><input type="text" value="'.$l->quantity.'" style="width:25px; height:25px;" id="menu'.$i.'"/></td>';
				echo ' <td class="update"><a href="#" id="update'. $i .'" onclick="updateQty('. $i.','.$l['id'].',document.getElementById(\'menu'.$i.'\').value)">Update</a></td>';
		        echo '<td class="add"><a href="#"><img id="img'.$i.'" src="'. ApplicationConfig::app()->params["theme"]["imageUrl"].'deleted.png" /></a></td>';
	    		echo "</tr>";
				echo "<script type='text/javascript'>";
				echo 'jQuery(function($) {
						jQuery(\'body\').undelegate(\'#img'. $i .'\',\'click\').delegate(\'#img'.$i.'\',\'click\',function(){jQuery.ajax({\'url\':\''.Yii::app()->createUrl('site/deleteItem/id/'.$l['id']).'\',\'cache\':false,\'success\':function(html){jQuery("#order_list").html(html)}});return false;})
					});';       
				echo "</script>"; 
	    		$i++;
	    	}
	    	echo "</table>";
			
	    	$total = $total;
	    	echo "<div class='total'><div class='left'>Sub-total:</div>
	            <div class='right'>Rs. ".$total. "</div> 
	        </div>";
			
	    	if($rest_model->minimum_order < $total)
	    	{
	    		if($rest_model->discount_type == "flat")
	    			$discounts = $rest_model->discount_value;
	    		if($rest_model->discount_type == "percentage")	 
	    			$discounts = $total * $rest_model->discount_value / 100;
	    	}
	    	else 
	    		$discounts = 0;
	    	
	    	echo "<div class='total'><div class='left'>Discounts:</div>
	            <div class='right'>Rs. ".$discounts. "</div> 
	        </div>";
	    	
	        echo "<div class='total'><div class='left'>Taxes:</div>
	            <div class='right'>Rs. ". ($total - $discounts) * $rest_model->tax / 100 ."</div>
	        </div>";
	        
	        echo "<div class='total' style='background:#c4c4c4'>
	        	<div class='left'>Total:</div>
	            <div class='right'>Rs. ".($total - $discounts + (($total - $discounts) * $rest_model->tax/100))."</div> 
	        </div>";
	    	Yii::app()->end();
		}
		else 
		{
			$cart_id = ApplicationSessions::run()->read('cart_id');
		
			if(!isset($cart_id))
			{
				$maxID = Yii::app()->db->createCommand()
	  							->select('max(id) as max')
	  							->from('cart')
	  							->queryScalar();
	  			$maxID = $maxID+1;
	  			
				ApplicationSessions::run()->write('cart_id',$maxID);
			}
			$model = Restaurant::model()->findByPk($restaurant);
			//$veg_categories = RestaurantMenuMapping::getList('RESTAURANT-VEG', array('id'=>$restaurant));
			//$non_veg_categories = RestaurantMenuMapping::getList('RESTAURANT-NON-VEG', array('id'=>$restaurant));
			echo '<script type="text/javascript">';
			echo 'window.parent.location.href="'.Yii::app()->createUrl("site/restaurant/id/".$model->slug."/price/".$price).'";</script>'; 
			//$this->render('restaurant', array('model'=>$model, 'veg_categories'=>$veg_categories, 'non_veg_categories'=>$non_veg_categories));
		}
    }
    
    public function actionAddToFav()
    {
    	$restid="";
    	if (isset($_GET))
    	foreach ($_GET as $key=>$value)
    	$restid=$key;
    	
    	if ($restid) {
    		$fav= new Favorites();
    		$fav->id_restaurant=$restid;
    		$fav->id_customer="1";
    		$fav->save();
    		echo "added";
    	}
    	
    }

public function actionFblogin(){

/*                 
         if($this->_identity===null)
        {     
           // $this->_identity=new FBIdentity($_GET['username'],$_GET['userid']);
           // $this->_identity->authenticate();
           // $this->_logouturl = $_GET['logout'];
$config = array(
    'appId' => '173271229456237',
    'secret' => '604042cf852163b2fad38e1ec1d51a3e',
  );

  $facebook = new Facebook($config);
  $user_id = $facebook->getUser();

    if($user_id) {

      // We have a user ID, so probably a logged in user.
      // If not, we'll get an exception, which we handle below.
      try {                                               

        $user_profile = $facebook->api('/me','GET');
        //echo "Name: " . $user_profile['name'];
        echo $user_profile['first_name'] . " " . $user_profile['last_name'] ."<br/>";
        echo $user_profile['email'];
        //echo "<pre>";
        //print_r($user_profile);
        

      } catch(FacebookApiException $e) {
        // If the user is logged out, you can have a 
        // user ID even though the access token is invalid.
        // In this case, we'll get an exception, so we'll
        // just ask the user to login again here.
        $login_url = $facebook->getLoginUrl(); 
        echo 'Please <a href="' . $login_url . '">login.</a>';
        echo($e->getType());
        echo($e->getMessage());
      }   
    } else {

      // No user, print a link for the user to login
      $login_url = $facebook->getLoginUrl();
      echo 'Please <a href="' . $login_url . '">login.</a>';

    }              */
 
            $error = 0;
           
            //if($error===FBIdentity::ERROR_NONE){
                
            $customer = Customers::model()->findByAttributes(array('email_address'=>$_GET['username']));
            //echo $customer->firstname; exit;  
      			if(empty($customer) || !isset($customer))
      			{
      				$customer = new Customers();
      				$customer->email_address=$_GET['username'];
      				$customer->firstname=$_GET['fname'];
      				$customer->lastname=$_GET['lname'];
  	    			$customer->created = date('Y-m-d H:i:s');
  	    			$customer->modified = date('Y-m-d H:i:s');      
  	    			$customer->status = 'active';
  	    			$customer->mobile_no = 0;
  	    			$customer->date_of_birth = '0000-00-00';   
  	    			if($customer->validate())
  	    			{
  	    				//$validate = true;    
  	    				$customer->save();
  	    			}
  	    			else
  	    			{
  	    			  print_r($customer->getErrors()); exit;
              }
      			}                                  
    			//ApplicationSessions::run()->write('customer_id',$_GET['username']);
    			  
            ApplicationSessions::run()->write('customer_id',$customer->id);

            $session = new CHttpSession();
            $session->open();
            //$session['referer_uri']
            //$this->redirect(Yii::app()->homeUrl);
            if(isset($session['referer_uri']))
            {
              $url = $session['referer_uri']; 
            }  
            else
            {
               $url = Yii::app()->homeUrl;
            }
            echo '<script>window.parent.location.href="'.$url.'"</script>';
            //}else{
            //return false;
            //}       
        //}    
		}
		
	public function actionGoogleLogin()
	{
		$this->render('googlelogin');
	}
	
	public function actionPage($slug)
	{
		$model=StaticPages::model()->getModel('BY-SLUG',array('slug'=>$slug));
		if (!empty($model))
		$this->render('staticpages',array('model'=>$model));
	}
	
	public function actionHomePageLogin($id=null) 
    {
    	if(isset($_POST['login']))
    	{
    		$flag = 0;
    		$username = $_POST['username'];
    		$password = $_POST['password'];
    		
    		$model = Customers::model()->findByAttributes(array('email_address'=>$_POST['username']));
    		if($model != null)
    		{
    			if(md5($password) == $model->password)
    			{
    				ApplicationSessions::run()->write('customer_id',$model->id);
    				
	    			if(isset($id) || $id != "")
	    			{
	    				$this->redirect(array('index'));
	    			}
    			}
    			else 
    				$flag = 1;
    		}
    		else 
    			$flag = 1;
    			
    		if($flag == 1)
    			Yii::app()->user->setFlash('loginMessage','Username/Password incorrect!');
    		
    	}
    	$this->redirect(array('index'));
    }
    public function actionDeliveryArea($id)
    {
    	//$this->layout="";
    	$result = "";
    	$slug = "";
		if (!empty($_POST))
		{
			if (!empty($_POST['loc_type']) && !empty($_POST['loc_id']))
			{
				if ($_POST['loc_type']=="zone")
				{
					$objZone = Zones::model()->getModel("BY-SLUG", array('slug'=>$_POST['loc_id']));
					$objRestaurant = Restaurant::model()->getModel("BY-ID", array('id'=>$id));
					$arrDeliveryAreas = explode(",", $objRestaurant->delivery_areas);
					
					if(in_array($objZone->id, $arrDeliveryAreas))
					$result = "success";
					else
					$result = "unsuccessful";
					$slug = $objRestaurant->slug;
				}
			}
		}
		$this->render('deliveryarea',array('result'=>$result,'slug'=>$slug));    
    }
    public function actionPaymentFailure($order_id)
    {
    	$this->render('paymentfailure',array('order_id'=>$order_id));
    }
    
    public function actionAttributesForm($id, $restaurant_id)
    {
    	$this->layout = 'fancylayout';
    	$list = ItemAttributeRestaurantMapping::getList('RESTAURANT-ATTRIBUTES-1', array('id'=>$id,'restaurant_id'=>$restaurant_id));
    	
    	if(isset($_POST['Add']))
		{
			$price = 0;
			$str = "";
			
			if(!empty($_POST['options']))
			{
				$options = trim($_POST['options'],",");
				$arr = explode(",", $options);
				
				foreach ($arr as $option )
	    		{
					$model = ItemAttributeRestaurantMapping::model()->findByAttributes(array('restaurant_id'=>$restaurant_id, 'item_id'=>$id, 'attribute_level_2_id'=>$option));
					if(!isset($model->price))
						$model->price = 0;
					$price = $price + $model->price;
					$str .= ",".$option;
	    		} 
			}
			
			if(!empty($_POST['items']))
			{
				foreach ( $_POST['items'] as $field )
	    		{
	    			$str .= ",".$field;
	    			$item = ItemAttributeRestaurantMapping::model()->findByAttributes(array('restaurant_id'=>$restaurant_id, 'item_id'=>$id, 'attribute_level_2_id'=>$field));
	    			$price = $price + $item->price; 
	    		}
			}
			
			if($str != "")
				$str = $str.",";
			$this->redirect(array('addToCart','id'=>$id,'restaurant'=>$restaurant_id,'qty'=>'1','price'=>$price,'attr_list'=>$str));
/*			$rest = Restaurant::model()->findByPk($restaurant_id);
			$this->forward(Yii::app()->createUrl('site/addToCart/id/'.$id.'/restaurant/'.$restaurant_id.'/qty/1/price/'.$price),false);		
			$this->redirect(array('restaurant','id'=>$rest->slug));*/
		}
		
    	$this->render('attributesForm',array('list'=>$list,'id'=>$id,'restaurant_id'=>$restaurant_id));	
    }

    
    public function actionVieworder($order_id)
    {
    	$this->layout = "fancylayout";
    	$model = Orders::model()->findByPk($order_id);
    	$this->render('vieworder',array('order_id'=>$order_id,'model'=>$model));
    }
    	public function actionError()
	{
    
	    if($error=Yii::app()->errorHandler->error)
	    {
	    	if(Yii::app()->request->isAjaxRequest)
	    		echo $error['message'];
	    	else
	        	$this->render('error', $error);
	    }
	}

}